package ru.ifmo.rybakov.muclumon.analysis;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.ifmo.rybakov.muclumon.PropertyValueFactory;
import ru.ifmo.rybakov.muclumon.Task;

public class FileEntityManager {
	private static Logger logger = LoggerFactory.getLogger(FileEntityManager.class);
	
	private final Set<Task> tasks = new HashSet<Task>();
	
	public void read(String path) {
		try {
			BufferedReader br = new BufferedReader(new FileReader(path));
			String line;
			Task task = null;
			while ((line = br.readLine()) != null) {
				if ("".equals(line)) continue; // skip empty lines
				String[] parts = line.split("\t");
				if (parts.length != 2) {
					logger.warn("Invalid line, skipping: {}", line);
					continue;
				}
				String name = parts[0];
				String value = parts[1];
				if ("task".equals(name)) { // create new task
					task = new Task(value);
					tasks.add(task);
				} else { // add property to task
					if (task == null) {
						logger.warn("No task defined for property: {}", line);
						continue;
					}
					task.addPropertyValue(PropertyValueFactory.create(name, value));
				}
			}
			br.close();
		} catch (IOException e) {
			logger.error("I/O exception", e);
		}
	}
	
	public Set<Task> getTasks() {
		return Collections.unmodifiableSet(tasks);
	}
}
